package com.sangeng.interceptor;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取用户名,判断是否存在
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (StringUtils.isEmpty(username)) {
            //获取项目路径
            String contextPath = request.getServletContext().getContextPath();
            //如果获取不到说明未登录,跳转登录页面
            response.sendRedirect(contextPath + "/static/login.html");
        } else {
            //获取到了说明登陆过了,放行
            return true;
        }

        return false;
    }


}
